let settingHandler = function () {

}

settingHandler.prototype.LocateMenu = function () {
    let url = window.location.href;
    let menu_item = $('.menu-item');
    menu_item.removeClass('active');
    if (url.indexOf('person_info') >= 0) {
        // 为账号信息菜单项添加active类
        menu_item.eq(0).addClass('active');
    } else if (url.indexOf('set_count') >= 0) {
        // 为账号设置菜单项添加active类
        menu_item.eq(1).addClass('active');
    } else if (url.indexOf('/post/manage/') >= 0) {
        // 为帖子管理菜单项添加active类
        menu_item.eq(2).addClass('active');
    } else if (url.indexOf('/post/like/') >= 0) {
        // 为喜欢的帖子菜单项添加active类
        menu_item.eq(3).addClass('active');
    }

};

settingHandler.prototype.SetCount = function () {
    $(document).ready(function () {
        // 头像上传
        $('#upload-avatar-btn').click(function () {
            $('#avatar-input').click();
        });

        $('#avatar-input').change(function () {
            var file = this.files[0];
            if (file) {
                var formData = new FormData();
                formData.append('avatar', file);

                csrf_ajax.ajax({
                    url: '/avatar/upload/',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        if (response.code === 200) {
                            $('#avatar-preview').attr('src', '/media/avatar/' + response.data.avatar);
                            $('#user-avatar').attr('src', '/media/avatar/' + response.data.avatar);
                        } else {
                            xtalert.alertErrorToast('上传失败：' + response.message);
                        }
                    },
                    error: function () {
                        xtalert.alertNetworkError();
                    }
                });
            }
        });

        // 保存修改
        $('#save-count').click(function (event) {
            event.preventDefault();
            let username = $('#username').val().trim();
            let signature = $("#signature").val();
            if (!username) {
                xtalert.alertInfoToast('请输入用户名');
                return;
            }
            csrf_ajax.post({
                "url": "/settings/set_count/",
                "data": {
                    username,
                    signature,
                },
                "success": function (data) {
                    if (data.code === 200) {
                        xtalert.alertSuccessToast('修改成功');
                    } else {
                        xtalert.alertErrorToast(data.message);
                    }
                },
                "fail": function () {
                    xtalert.alertNetworkError();
                }
            });
        });

        // 取消修改
        $("#cancel-btn").click(function () {
            window.location.reload();
        })
    });
};

settingHandler.prototype.OldEmailCaptcha = function () {
    let callback = function (event) {
        let $this = $(this);
        csrf_ajax.post({
            url: "/settings/set_count/change_email/",
            date: {},
            success: function (data) {
                if (data['code'] === 200) {
                    console.log("验证码发送成功！");
                    // 取消按钮的点击事件
                    $this.off("click");
                    // 添加禁用状态
                    $this.attr("disabled", "disabled");
                    // 开始倒计时
                    let countdown = 60;
                    let interval = setInterval(function () {
                        if (countdown > 0) {
                            $this.text(countdown);
                        } else {
                            $this.text("发送验证码");
                            $this.attr("disabled", false);
                            $this.on("click", callback);
                            // 清理定时器
                            clearInterval(interval);
                        }
                        countdown--;
                    }, 1000);
                } else {
                    alert(data["message"]);
                }
            }
        })
    }
    $("#send-captcha").on("click", callback);
};

settingHandler.prototype.CheckOldEmailCaptcha = function () {
    $("#next").click(function (event) {
        event.preventDefault();
        let captcha = $("#captcha")
        if (captcha.val() === "") {
            xtalert.alertInfoToast("请输入验证码！");
            return;
        }
        csrf_ajax.post({
            "url": "/settings/set_count/change_email/check_captcha/",
            "data": {
                "captcha": captcha.val()
            },
            "success": function (data) {
                if (data.code === 200) {
                    window.location.href = "/settings/set_count/change_email/new_email/";
                } else {
                    xtalert.alertError(data.message);
                    captcha.val("");
                }
            },
            "fail": function () {
                xtalert.alertNetworkError();
            }
        });
    });
};

settingHandler.prototype.NewEmailCaptcha = function () {
    let callback = function (event) {
        event.preventDefault();
        let $this = $(this);
        let new_email = $("#new-email").val();
        console.log(new_email)

        if (!new_email) {
            xtalert.alertInfoToast("请输入邮箱");
            return;
        } else if (!/^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/.test(new_email)) {
            xtalert.alertInfoToast("请输入正确格式的邮箱");
            return;
        }

        csrf_ajax.post({
            url: "/settings/set_count/change_email/new_email/",
            data: {
                "email": new_email,
            },
            success: function (data) {
                if (data['code'] === 200) {
                    console.log("验证码发送成功！");
                    // 取消按钮的点击事件
                    $this.off("click");
                    // 添加禁用状态
                    $this.attr("disabled", "disabled");
                    // 开始倒计时
                    let countdown = 60;
                    let interval = setInterval(function () {
                        if (countdown > 0) {
                            $this.text(countdown);
                        } else {
                            $this.text("发送验证码");
                            $this.attr("disabled", false);
                            $this.on("click", callback);
                            // 清理定时器
                            clearInterval(interval);
                        }
                        countdown--;
                    }, 1000);
                } else {
                    xtalert.alertInfoToast(data["message"]);
                }
            },
            "fail": function () {
                xtalert.alertNetworkError();
            }
        })
    }
    $("#send-new—email-captcha").on("click", callback);
};

settingHandler.prototype.CheckNewEmailCaptcha = function () {
    $("#save-new-email").click(function (event) {
        event.preventDefault();
        let email = $("#new-email").val();
        let captcha = $("#captcha");
        if (captcha.val() === "") {
            xtalert.alertInfoToast("请输入验证码！");
            return;
        }
        csrf_ajax.post({
            "url": "/settings/set_count/change_email/verify_new_email/",
            "data": {
                "email": email,
                "captcha": captcha.val()
            },
            "success": function (data) {
                if (data.code === 200) {
                    xtalert.alertSuccessToast("修改成功！");
                    setTimeout(function () {
                        window.location.href = "/settings/set_count/";
                    }, 1500)
                } else {
                    xtalert.alertError(data.message);
                }
            },
            "fail": function () {
                xtalert.alertNetworkError();
            }
        });
    });
};

settingHandler.prototype.DeletePost = function () {
    let self = this;
    $(".delete-post").click(function (event) {
        event.preventDefault();
        let $this = $(this);
        let post_id = $this.attr("data-post-id");
        let postItem = $this.closest('.post-item');

        xtalert.alertConfirm({
            "msg": "确定要删除这篇帖子吗？",
            "confirmCallback": function () {
                self.deletePostAjax(post_id, postItem);
            }
        });
    });
};

settingHandler.prototype.deletePostAjax = function (postId, postItem) {
    let self = this;
    csrf_ajax.post({
        "url": "/settings/post/delete/",
        "data": {
            "post_id": postId
        },
        "success": function (res) {
            if (res.code === 200) {
                //从DOM中移除元素
                postItem.slideUp(300, function () {
                    xtalert.alertSuccessToast("删除成功！");
                    $(this).remove();
                    // 检查是否需要更新分页
                    setTimeout(function (){
                        self.checkPagination();
                    }, 100);
                });

            } else {
                xtalert.alertErrorToast(res.message);
            }
        },
        "fail": function () {
            xtalert.alertNetworkError();
        }
    });
};

settingHandler.prototype.checkPagination = function () {
    // 检查是否需要处理分页逻辑
    if ($('.post-item').length === 0) {
        let currentUrl = new URL(window.location);
        let currentPage = parseInt(currentUrl.searchParams.get('page')) || 1;

        if (currentPage > 1) {
            currentUrl.searchParams.set('page', currentPage - 1);
            window.location.href = currentUrl.toString();
        }
    }
};

settingHandler.prototype.CancelLike = function () {
    $(function () {
        if ($('.liked-post-item').length === 0) {
            $('#empty-state-template').css('display', 'block')
        }
    });


    $(document).on("click", "#cancel-liked-btn", function (event) {
        let self = $(this);
        event.preventDefault();
        let post_id = $("#cancel-liked-btn").attr("data-post-id");
        let postItem = self.closest('.liked-post-item');
        if (!post_id) {
            xtalert.alertInfoToast("请传入帖子id");
            return;
        }
        csrf_ajax.post({
            "url": "/settings/post/like/",
            "data": {
                "post_id": post_id
            },
            success: function (data) {
                if (data.code === 200) {
                    postItem.slideUp(300, function () {
                        $(this).remove();
                        // 检查是否还有点赞的帖子，如果没有显示空状态
                        if ($('.liked-post-item').length === 0) {
                            $('#empty-state-template').css('display', 'block')
                        }
                    });
                } else {
                    xtalert.alertErrorToast(data.message);
                }
            },
            fail: function () {
                xtalert.alertNetworkError();
            }
        })
    });
};


settingHandler.prototype.run = function () {
    this.LocateMenu();
    this.SetCount();
    this.OldEmailCaptcha();
    this.CheckOldEmailCaptcha();
    this.NewEmailCaptcha();
    this.CheckNewEmailCaptcha();
    this.DeletePost();
    this.CancelLike();
};

$(function () {
    let handler = new settingHandler();
    handler.run();
})